from flask import Blueprint, jsonify, request
from db import db1
from werkzeug.security import generate_password_hash, check_password_hash
import json

bp_auser = Blueprint("bp_auser", __name__)


# 初始化数据
@bp_auser.route('/reg')
def reg():
    password = generate_password_hash('123')
    sql1 = "insert into auser values(0,'zs','%s','湖人总冠军')" % (password)
    db1.insert(sql1)

    sql2 = "insert into auser values(0,'li','%s','中国军团冲冲冲')" % (password)

    db1.insert(sql2)
    return 'ok'


# 登录接口
@bp_auser.route('/login', methods=['POST'])
def login():
    # 获取用户名密码
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    # 去数据查询根据用户名
    sql = "select * from auser where username='%s'" % (data['username'])
    res = db1.find(sql)
    # 比对密码
    if res:
        # 返回结果，userid
        if check_password_hash(res['password'], data['password']):
            return jsonify({"code": 200, 'userid': res['id'],'username':res['username'],'sign':res['sign']})
        else:
            return jsonify({"code": 10010, 'mes': '密码错误'})
    return jsonify({"code": 10011, 'mes': '用户不存在'})


def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


@bp_auser.route('/articleM', methods=['POST', 'GET'])
def articleM():
    if request.method == "POST":
        # 获取用户输入
        data = get_data()
        # 构造sql添加
        sql = "insert into article(title,content,userid) values('%s','%s',%d)" % (
        data['title'], data['content'], int(data['userid']))
        db1.insert(sql)
        # 返回结果
        return jsonify({"code": 200})
    else:
        # 判断获取所有文章还是我的文章
        uid = int(request.args.get('uid'))
        if uid > 0:
            sql = "select * from article where userid=%d" % (int(uid))
        else:
            sql = "select * from article"
        res = db1.findall(sql)
        return jsonify({"code": 200, 'list': res})